import React, { Component } from 'react'
import {
  StyleSheet,
  ScrollView,
  FlatList,
  TouchableOpacity,
  View,
  Text,
  TextInput,
  KeyboardAvoidingView
} from 'react-native'
import { connect } from 'react-redux'

import Toast from 'react-native-simple-toast'
import { theme_app, theme_text } from '../../utils/appTheme'
import HeaderDefault from '../../components/header/HeaderDefault'
import { dateTransform } from '../../utils/commonMethod'
import { addSign, getPatientOfMyWard } from '../../netServer/signs_net'
import { isNotEmptyString } from '../../utils/structureJudgment'

import Button from "../../components/Button";




class SignsEentry extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isCommiting: false,
      patientList: [],
      patentCurrentSelete: {},
      body_height: '', //身高
      body_weight: '', //体重
      body_temperature: '', //体温
      body_heartRate: '', //心率
      body_pulse: '', //脉搏
      body_breathing: '', //呼吸
      body_bowelMovement: '', //大便
      body_bloodPressure: '', //血压

      pinfo_hosNum: '',
      pinfo_bed: '',
      pinfo_name: '',
      pinfo_age: '',
      pinfo_sex: '',

    }
  }

  static navigationOptions = ({ navigation }) => ({
    header: (
      <HeaderDefault
        title="体征录入"
        backBtnOnPress={() => {
          navigation.goBack()
        }}
      />
    )
  })

  componentDidMount() {
    this._loadPatinetListWithUserName()
  }

  _loadPatinetListWithUserName = () => {
    let paramss = new FormData()
    paramss.append('userName', this.props.user_info.user_name)


    getPatientOfMyWard(paramss, resp => {


      let { code, data = [], msg } = resp
      // let { code, data = [], msg } = ttd



      if (code == '0') {
        this.setState({
          patientList: data
        })
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
      }
    })
  }

  _commitTiZhen = () => {
    if (!this.state.patentCurrentSelete.patient_no) {
      Toast.showWithGravity('请选择患者', 0.3, Toast.CENTER)
      return
    }

    let paramss = new FormData()
    paramss.append('userId', this.props.user_info.user_id)
    paramss.append('patientNo', this.state.patentCurrentSelete.patient_no)
    paramss.append(
      'recordDate',
      dateTransform(new Date(), 'yyyy-MM-dd hh:mm:ss')
    )

    let subData = [
      {
        name: '身高',
        value: this.state.body_height
      },
      {
        name: '体重',
        value: this.state.body_weight
      },
      {
        name: '体温',
        value: this.state.body_temperature
      },
      {
        name: '心率',
        value: this.state.body_heartRate
      },
      {
        name: '脉搏',
        value: this.state.body_pulse
      },
      {
        name: '呼吸',
        value: this.state.body_breathing
      },
      {
        name: '大便',
        value: this.state.body_bowelMovement
      },
      {
        name: '血压',
        value: this.state.body_bloodPressure
      }
    ]

    let markidx = 0

    for (let index = 0; index < subData.length; index++) {
      const element = subData[index]
      if (isNotEmptyString(element.value)) {
        paramss.append('data[' + markidx + '][name]', element.name)
        paramss.append('data[' + markidx + '][value]', element.value)
        markidx++
      }
    }

    // paramss.append('data', subData)

    this.setState({
      isCommiting: true,
    })




    addSign(paramss, resp => {
      this.setState({
        isCommiting: false,
      })
      let { code, data, msg } = resp
      if (code == '0') {
        this.setState({
          body_height: '', //身高
          body_weight: '', //体重
          body_temperature: '', //体温
          body_heartRate: '', //心率
          body_pulse: '', //脉搏
          body_breathing: '', //呼吸
          body_bowelMovement: '', //大便
          body_bloodPressure: '' //血压
        })
        Toast.showWithGravity('提交成功', 0.3, Toast.CENTER)
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
      }
    })
  }

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: '#efefef' }} />
  }

  _keyExtractor = (item, index) => item.patient_no

  _renderItem = ({ item }) => {
    let isSeleted =
      item.patient_no === this.state.patentCurrentSelete.patient_no
    let seletedStyle = isSeleted
      ? { padding: 10, backgroundColor: '#D1EEEE' }
      : { padding: 10 }
    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({
            patentCurrentSelete: item
          })
        }}
        style={seletedStyle}
      >
        <Text style={{ fontSize: 15 }}>{item.name}</Text>

        <View
          style={{
            paddingTop: 10,
            paddingBottom: 10,
            flexDirection: 'row',
            justifyContent: 'space-between'
          }}
        >
          <Text style={{ fontSize: 12 }}>
            {item.sex == 1 ? '男' : '女'}/{item.age}
          </Text>
          <Text>{item.bed_no}</Text>
        </View>

        <Text style={{ color: 'green' }}>{item.gradeName}</Text>
        <Text style={{ color: 'red', paddingTop: 10 }}>{item.allergy}</Text>
      </TouchableOpacity>
    )
  }

  _renderInputItem(titele, unit, inputeValue, textInputChange) {
    return (
      <View
        style={{
          borderBottomColor: '#dfdfdf',
          borderBottomWidth: 1,
          flexDirection: 'row'
        }}
      >
        <View
          style={{
            width: 50,
            height: 52,
            alignItems: 'center',
            justifyContent: 'center',
            borderRightWidth: 1,
            borderRightColor: '#dfdfdf'
          }}
        >
          <Text style={{ lineHeight: 20 }}>{titele}</Text>
          <Text style={{ lineHeight: 20, color: '#EE3B3B' }}>{unit}</Text>
        </View>
        <View
          style={{
            alignItems: 'center',
            justifyContent: 'center',
            paddingLeft: 5
          }}
        >
          <TextInput
            style={{
              width: 0.6 * screenWidth - 55,
              height: 40
            }}
            value={inputeValue}
            onChangeText={textInputChange}
            keyboardType={
              titele === '血压' ? 'numbers-and-punctuation' : 'numeric'
            }
            underlineColorAndroid="transparent"
            selectionColor="rgb(35,151,246)"
            clearButtonMode="while-editing"
          />
        </View>
      </View>
    )
  }

  render() {
    return (
      <KeyboardAvoidingView
        keyboardVerticalOffset={60}
        behavior="padding"
        style={{
          width: screenWidth,
          height: screenHeight - 64
        }}
      >
        <ScrollView
          keyboardShouldPersistTaps="always"
          keyboardDismissMode="on-drag"
          style={{ flex: 1, backgroundColor: theme_app.bg_color }}
          style={{ width: screenWidth, height: screenHeight - 64 }}
        >
          <View
            style={{
              width: screenWidth,
              height: screenHeight - 109,
              flexDirection: 'row'
            }}
          >
            <View
              style={{ width: 0.4 * screenWidth, height: screenHeight - 109 }}
            >
              <FlatList
                style={{
                  width: 0.4 * screenWidth,
                  height: screenHeight - 109
                }}
                ItemSeparatorComponent={this._separator}
                data={this.state.patientList}
                keyExtractor={this._keyExtractor}
                renderItem={this._renderItem}
              />
            </View>
            <View
              style={{
                width: 0.6 * screenWidth,
                height: screenHeight - 109,
                backgroundColor: 'white',
                borderLeftWidth: 1,
                borderLeftColor: '#9b9b9b'
              }}
            >
              {this._renderInputItem(
                '身高',
                'cm',
                this.state.body_height,
                text => {
                  this.setState({ body_height: text })
                }
              )}
              {this._renderInputItem(
                '体重',
                'kg',
                this.state.body_weight,
                text => {
                  this.setState({ body_weight: text })
                }
              )}

              {this._renderInputItem(
                '体温',
                '℃',
                this.state.body_temperature,
                text => {
                  this.setState({ body_temperature: text })
                }
              )}
              {this._renderInputItem(
                '心率',
                '次/分',
                this.state.body_heartRate,
                text => {
                  this.setState({ body_heartRate: text })
                }
              )}
              {this._renderInputItem(
                '脉搏',
                '次/分',
                this.state.body_pulse,
                text => {
                  this.setState({ body_pulse: text })
                }
              )}
              {this._renderInputItem(
                '呼吸',
                '次/分',
                this.state.body_breathing,
                text => {
                  this.setState({ body_breathing: text })
                }
              )}
              {this._renderInputItem(
                '大便',
                '次/日',
                this.state.body_bowelMovement,
                text => {
                  this.setState({ body_bowelMovement: text })
                }
              )}
              {this._renderInputItem(
                '血压',
                'mmHg',
                this.state.body_bloodPressure,
                text => {
                  this.setState({ body_bloodPressure: text })
                }
              )}
            </View>
          </View>

          <Button
            isLoading={this.state.isCommiting}
            isLoadStr="提交中..."
            style={{
              width: screenWidth,
              height: 45,
              backgroundColor: '#00CD00',
              justifyContent: 'center',
              alignItems: 'center'
            }}
            onPress={this._commitTiZhen}
          >
            <Text
              style={{
                fontSize: 20,
                color: "white"
              }}
            >
              提交
            </Text>
          </Button>


          {/* <TouchableOpacity
            onPress={this._commitTiZhen}
            style={{
              width: screenWidth,
              height: 45,
              backgroundColor: '#00CD00',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text style={{ color: 'white', fontSize: 20 }}>提交1</Text>
          </TouchableOpacity> */}
        </ScrollView>
      </KeyboardAvoidingView>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: theme_app.bg_color
  },
  inputItem1: {
    flexDirection: 'row',
    width: screenWidth,
    height: 45,
    backgroundColor: 'white',
    borderBottomColor: theme_app.separationLine_color,
    borderBottomWidth: 1,
    paddingLeft: 15,
    paddingRight: 15,
    alignItems: 'center'
  },
  textInput: {
    color: 'gray',
    fontSize: theme_text.default_font,
    alignSelf: 'center',
    width: screenWidth - 150,
    height: 40
  }
})

function select(store) {
  return {
    user_info: store.userInfo.user_info
  }
}

export default connect(select)(SignsEentry)
